//  文章分类
var express = require('express')
var router = express.Router()
var links = require('./../models/link')
var multer = require('multer')
let fs = require('fs')
let path = require('path')
// var Collections = require('./../models/collection')

// 新建/修改/删除1级分类
router.post('/change1', function (req, res, next) {
	let { data } = req.body
	links.findOne(function (err0, doc0) {
		//【逻辑1】
		// 集合不存在，新建集合
		if (doc0 == '' || doc0 == null) {
            console.log(data)
            data.id = 1
            data.sort = 0
			links.create({ list: [data] }, function (err, doc) {
				if (err) {
					res.json({
						code: '201',
						data: null,
						message: err,
						success: false,
					})
				} else {
					res.json({
						code: '200',
						data: null,
						message: '成功',
						success: true,
					})
				}
			})
		} else {
			/**【逻辑2】
			 * 增加一级分类
			 */
		
				if (!data.id) {
					data.id =
						doc0.list[doc0.list.length - 1].id +1
					data.children = []
                    data.sort = 0
				}
		
			doc0.list.push(data)
			doc0.save(function (err1, doc1) {
				if (err1) {
					res.json({
						code: '201',
						data: null,
						message: err1,
						success: false,
					})
				} else {
					res.json({
						code: '200',
						data: null,
						message: '成功',
						success: true,
					})
				}
			})
		}
	})
})

// 新建/修改/删除链接
router.post('/change2', function (req, res, next) {
	let {url, name, typeId} = req.body.data
	links.findOne(function (err0, doc0) {
		
			/**【逻辑1】
			 * 修改/增加二级分类
			 */
			doc0.list.forEach((item,index)=>{
                if(item.id == typeId){
                    doc0.list[index].children.push({
                        url: url,
                        name: name,
                    })
                }
            })

     

			doc0.save(function (err1, doc1) {
				if (err1) {
					res.json({
						code: '201',
						data: null,
						message: err1,
						success: false,
					})
				} else {
					res.json({
						code: '200',
						data: null,
						message: '成功',
						success: true,
					})
				}
			})
		
	})
})

// 读取所有分类
router.get('/list', function (req, res, next) {
	links.findOne(function (err0, doc0) {
		if (err0) {
			res.json({
				code: '201',
				data: null,
				message: err0,
				success: false,
			})
			return false
		}
		res.json({
			code: '200',
			data: doc0,
			message: '成功',
			success: true,
		})
	})
})

// 删除分类
router.post('/delete', function (req, res, next) {
	let { id, childId } = req.body
	let wherestr = {
		id: 1,
	}
	links.remove(wherestr, function (err, doc) {
		doc.article[types].forEach((item, index) => {
			if (item.id == id) {
				doc.article[types].splice(index, 1)

				doc.save(function (err1, doc1) {
					if (err1) {
						res.json({
							status: '1',
							msg: '删除失败' + err1,
						})
					} else {
						res.json({
							status: '0',
							msg: '删除成功',
						})
					}
				})
			}
		})
	})
})

module.exports = router
